package ecoll.client.widgets;

import java.util.ArrayList;
import java.util.HashMap;

import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;

import ecoll.client.quiz.QuizUserData;

public class QuizRankingPanel extends VerticalPanel {

	public QuizRankingPanel(String roomName, ArrayList<QuizUserData> users) {
		HTML title = new HTML("<h3>" + roomName + " - ranking:</h3>");
		add(title);
		for (QuizUserData data : users)
			addUserRankData(data.getLogin(), data.getScore());
	}

	public void addUserScore(String login) {
		HorizontalPanel rankPanel = userRank.get(login);
		if (rankPanel != null) {
			setScore(rankPanel, getScore(rankPanel) + 1);
			correctRank(rankPanel);
		} else
			addUserRankData(login, 1);
	}

	public void addUserRankData(String login, int score) {
		HorizontalPanel rankPanel = new HorizontalPanel();
		Label scoreLabel = new Label("" + score);
		scoreLabel.setStyleName("rankScoreLabel");
		rankPanel.add(scoreLabel);
		Label loginLabel = new Label(login);
		loginLabel.setStyleName("rankLoginLabel");
		rankPanel.add(loginLabel);
		add(rankPanel);
		userRank.put(login, rankPanel);
		correctRank(rankPanel);
	}

	public void removeUserRankData(String login) {
		HorizontalPanel rankPanel = userRank.get(login);
		if (rankPanel != null) {
			userRank.remove(login);
			remove(rankPanel);
		}
	}

	private void correctRank(HorizontalPanel rankPanel) {
		int idx = getWidgetIndex(rankPanel);
		int score = getScore(rankPanel);
		for (int i = idx - 1; i > 0; --i) {
			HorizontalPanel prevRankPanel = (HorizontalPanel) getWidget(i);
			if (getScore(prevRankPanel) < score)
				insert(rankPanel, i);
			else
				break;
		}
	}

	private int getScore(HorizontalPanel rankPanel) {
		Label scoreLabel = (Label) rankPanel.getWidget(0);
		int score = Integer.parseInt(scoreLabel.getText());
		return score;
	}

	private void setScore(HorizontalPanel rankPanel, int score) {
		Label scoreLabel = (Label) rankPanel.getWidget(0);
		scoreLabel.setText("" + score);
	}

	private HashMap<String, HorizontalPanel> userRank = new HashMap<String, HorizontalPanel>();
}
